package com.example.myapplication2;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;

public class InetAddressActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_address;
    private TextView tv_desc;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inet_address);
        edit_address = findViewById(R.id.edit_address);
        tv_desc = findViewById(R.id.tv_desc);
        findViewById(R.id.btn_hostName_check).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_hostName_check:
                String hostName = edit_address.getText().toString();
                //开启子线程 检查主机名
                new CheckThread(hostName).start();
                break;
            default:
                break;
        }
    }
    //创建一个检查结果的接收器Handler
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            tv_desc.setText("主机检查结果如下：\n" + msg.obj);
            return true;
        }
    });

    private class CheckThread extends Thread {
        private String hostName;

        public CheckThread(@NonNull String name) {
            hostName = name;
        }

        @Override
        public void run() {
            //获得一个默认消息对象
            Message message = Message.obtain();
            try {
                URL url=new URL(hostName);
                URLConnection urlConnection = url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
                StringBuffer stringBuffer = new StringBuffer("");
                String read = null;
                while (null != (read = br.readLine())){
                    stringBuffer.append(read);
                }
                br.close();
                String desc = String.format("获取内容为\n%s", stringBuffer.toString());
                    message.what = 0; //消息类型
                    message.obj = desc;//消息描述

            } catch (Exception e) {
                e.printStackTrace();
                message.what = -1; //消息类型
                message.obj = e.getMessage(); //消息描述
            }
            // 向接收处理器发送检查结果消息
            handler.sendMessage(message);
        }
    }
}